from datetime import date
from typing import Counter
import requests
import time
from tqdm import tqdm
import pymysql
from pymysql.converters import escape_string
from requests.adapters import HTTPAdapter
import pandas as pd


def get_time(h):
    timeArray = time.localtime(h)
    otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
    print(otherStyleTime)

def get_token():
    url = 'https://hdgateway.zto.com/auth_account_loginByPassword'
    headers1 = {
        'Host': 'hdgateway.zto.com',
        'Connection': 'keep-alive',
        'Content-Length': '69',
        'sec-ch-ua': '"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"',
        'Accept': 'application/json, text/plain, */*',
        'x-token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ0aGlyZFBhcnR5U2lnbiI6IlVTRVJDRU5URVIiLCJhdWQiOiJXZWJVc2VyQ2VudGVyIiwic3ViIjoiMTc3NTA4ODA4IiwiY2xpZW50Q29kZSI6InBjIiwiaXNzIjoiV2ViVXNlckNlbnRlciIsImZhdCI6MTYyNTM2MDQ1MSwibW9iaWxlIjoiMTg3MTg4OTYzNzAiLCJleHAiOjE2MjUzODIwNTEsImlhdCI6MTYyNTM2MDQ1MSwidXNlcklkIjoiMTc3NTA4ODA4IiwianRpIjoiYWI5ZmZkNWU1NTYyNDBjYmJjN2JlYTA3M2FhNTZlZjIifQ.TZdMvfWizmzoI6dhfkfE64kXJIGEBMPlvfCuwohckkoUdgF-17WnbTsfr12HI-xiZ1vyDMS_3bccjjOnS-G-eh92_YiTVHcJHvr3llMY9Jhmu8aJ2ByTZRx8WQuXBNTaoz2KGMGN0vYkE0ZwHAhGFuvD5WIfiS2KbVOuzNK-AAFuBKKk4GxYOVu5yaEP3zyLKXzwXxUR20C_PX6Xl5g6yHH9XoiC32AxCPcZzx6jBNSWGOVldZdXpnBWbCcW64XwrMbxD8mTXlHBXMB-o2qsUBUuiwNoJdwMVwXnrjBlwLVQccbiWEJMd5R5Crik9fcyXXC9WWqa8IQirWt1tKU6pA',
        'x-clientCode': 'pc',
        'sec-ch-ua-mobile': '?0',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
        'Content-Type': 'application/json;charset=UTF-8',
        'Origin': 'https://auth.zto.com',
        'Sec-Fetch-Site': 'same-site',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Dest': 'empty',
        'Referer': 'https://auth.zto.com/',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9'
    }
    data = {"userName":"19924237889","password":"jfck2020","isAgainBind":False}
    response = requests.post(url,headers=headers1,data=data)
    # print(response.text)
    result = response.json()
    token = result['result']['token']
    return token


def get_data(pageIndex, f,token):
    url = 'https://hdgateway.zto.com/Order_GetReceiveList'
    headers2 = {
        'Host': 'hdgateway.zto.com',
        'Connection': 'keep-alive',
        'Accept': '*/*',
        'Access-Control-Request-Method': 'POST',
        'Access-Control-Request-Headers': 'authorization,content-type,x-token',
        'Origin': 'https://my.zto.com',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-site',
        'Sec-Fetch-Dest': 'empty',
        'Referer': 'https://my.zto.com/',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
    }
    res = requests.options(url,headers=headers2)
    headers3 = {
        'Authorization': 'Bearer ' + token,
        'Content-Type': 'application/json;charset=UTF-8',
        'Host': 'hdgateway.zto.com',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
        'X-TOKEN': token
    }
    data = '{"billStatus":[1,4,5,24,26,7],"keyword":"","pageIndex":'+ str(pageIndex) +',"pageSize":6}'
    try:
        response = request.post(url,headers=headers3,data=data,timeout=15)
    except:
        response = request.post(url,headers=headers3,data=data,timeout=15)
    result = response.json()
    s_url = 'https://hdgateway.zto.com/Order_QueryDetailByCode'
    # print(result)
    count = 1
    while result['message'] == '当前服务拥挤，请稍后重试':
        if count>3:
            return
        time.sleep(150)
        response = request.post(url,headers=headers3,data=data)
        result = response.json()
        if result['message'] != '当前服务拥挤，请稍后重试':
            break
        count = count + 1
    for item in result['result']['items']:
        data = {"billCode":item['waybillCode']}
        s_response = request.post(s_url,headers=headers3,data=data,timeout=15)
        print(s_response.json()['result'])
        result = s_response.json()['result']
        for key,value in result.items():
            if type(value)!='string':
                result[key] = str(value)  
        sql = 'insert into zt_data(id,senderAddress,recEmpDate,senderCounty,receiverProvince,receiverCounty,recSite,receiverCity,topVas,senderName,tradeBases,recMobile,recEmp,receiverName,receiverMobile,weight,senderMobile,senderProvince,senderCity,receiverAddress,vasCollectSum,waybillCode,orderCode,recSitePhone,category,vasResults) VALUES(null,%s, %s, %s, %s, %s, %s, %s, %s,%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
        value = (result['senderAddress'],result['recEmpDate'],result['senderCounty'],result['receiverProvince'],result['receiverCounty'],result['recSite'],result['receiverCity'],result['topVas'],result['senderName'],result['tradeBases'],result['recMobile'],result['recEmp'],result['receiverName'],result['receiverMobile'],result['weight'],result['senderMobile'],result['senderProvince'],result['senderCity'],result['receiverAddress'],result['vasCollectSum'],result['waybillCode'],result['orderCode'],result['recSitePhone'],result['category'],result['vasResults'])
        cur.execute(sql,value)
        connet.commit()

def get_wx_data():
    url = 'https://hdgateway.zto.com/Order_GetReceiveList'
    headers = {
        'Host':'hdgateway.zto.com',
        'x-version':'V7.37.1',
        'charset':'utf-8',
        'x-oid':'oJpUI0dfodWhZGal6OKgt9-M0qZI',
        'content-type':'application/json',
        'User-Agent':'Mozilla/5.0 (Linux; Android 7.1.2; TAS-AN00 Build/TAS-AN00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3770.143 Mobile Safari/537.36 MMWEBID/3766 MicroMessenger/8.0.3.1880(0x28000334) Process/appbrand0 WeChat/arm32 Weixin NetType/WIFI Language/zh_CN ABI/arm32 MiniProgramEnv/android',
        'x-token':'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ0aGlyZFBhcnR5U2lnbiI6IlVTRVJDRU5URVIiLCJhdWQiOiJXZWJVc2VyQ2VudGVyIiwic3ViIjoiMzEwNDA0MDMiLCJjbGllbnRDb2RlIjoicGMiLCJpc3MiOiJXZWJVc2VyQ2VudGVyIiwiZmF0IjoxNjI2MjUyNzU1LCJtb2JpbGUiOiIxOTkyNDIzNzg4OSIsImV4cCI6MTYyNjI3NDM1NSwiaWF0IjoxNjI2MjUyNzU1LCJ1c2VySWQiOiIzMTA0MDQwMyIsImp0aSI6IjFmMTFkYjYxZjAyYzQ2OTJhOWVhZGNjZDhiMWNmOGYxIn0.yRmsdU1Nlf-WGok9dxsDD5jix0paMAoGZzAGmOYgeEaPxJFfmA-_h3alktEQiO_-oY5V9NG85OOl4lZ0AYUcTGIpRv4xFy44jaBrGzDpSAVJpFhAry7gSXFH1AMys6zzgZjb3daTaHws_drC9bbtR4t_djWTfUubSWIH7gHc50H5pXFWcIJLM00-fuJhrJ2x0BnWStTItwqmnzUKmlv56Epm-NWwq_ANnkmZxeKBugYrbVoHLiPzbd7q1qPbk0EBcNfXdamQx9ICS1ZwSI97YlteeaPpArvTacuLvoV7tas2HIJHJi0znlnAwqiZjkQ10MY87chAq0C4j_2twH1uZQ',
        'Accept-Encoding':'gzip,compress,br,deflate',
        'x-clientcode':'wechatMiniZtoHelper',
        'Referer':'https://servicewechat.com/wx7ddec43d9d27276a/223/page-frame.html',
        'Connection':'keep-alive',
    }
    data = '{"pageIndex":1,"pageSize":6,"keyword":"","startTime":null,"endTime":null,"billStatus":[1,4,5,24,26,7]}'
    res = request.post(url,headers=headers,data=data)
    print(res.json())


def get_wx_detail(id):
    url = 'https://hdgateway.zto.com/searchOrderDetailByOrderCodeOrBillCode'
    headers = {
        'Host':'hdgateway.zto.com',
        'x-version':'V7.37.1',
        'charset':'utf-8',
        'x-oid':'oJpUI0dfodWhZGal6OKgt9-M0qZI',
        'content-type':'application/json',
        'User-Agent':'Mozilla/5.0 (Linux; Android 7.1.2; TAS-AN00 Build/TAS-AN00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3770.143 Mobile Safari/537.36 MMWEBID/3766 MicroMessenger/8.0.3.1880(0x28000334) Process/appbrand0 WeChat/arm32 Weixin NetType/WIFI Language/zh_CN ABI/arm32 MiniProgramEnv/android',
        'x-token':'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ0aGlyZFBhcnR5U2lnbiI6IlVTRVJDRU5URVIiLCJhdWQiOiJXZWJVc2VyQ2VudGVyIiwic3ViIjoiMzEwNDA0MDMiLCJjbGllbnRDb2RlIjoicGMiLCJpc3MiOiJXZWJVc2VyQ2VudGVyIiwiZmF0IjoxNjI2MzEzODUzLCJtb2JpbGUiOiIxOTkyNDIzNzg4OSIsImV4cCI6MTYyNjMzNTQ1MywiaWF0IjoxNjI2MzEzODUzLCJ1c2VySWQiOiIzMTA0MDQwMyIsImp0aSI6IjJiNGQzMGE5OWUxODQzZjFhNWIxMjc2YmEyNWVlMjdkIn0.cKAbS1MBY-jA_d_STQiapl0TCYCeUvBqZT-jD7Mcxo0OKnAbGTyp-SodQB_O5nexLntfNeAt8HNobJTDQB_AvJkelH5EA9X92rFdwutVytbHDp8xlbELyIQU5nggu2F-1m-Qj7oBqA5Cl6PSpEfJ9MKcEo32IlVChbKUGus-EDKcJPOiHjokRCBEYetWUEp0u6NfjWs4rMYK5gYyDmaIUSt3nPLUQAXTTOvFEgIRcGrx9igB2qKE-j3Bt6T3wreYzNwv2h0KZPfwFFLEdddmTIk_oyIwwvP9Rd2xijOm9cZn6c1bi7_jjXcSumlE1rSbNj2lerT_bPlkWletKOQATQ',
        'Accept-Encoding':'gzip,compress,br,deflate',
        'x-clientcode':'wechatMiniZtoHelper',
        'Referer':'https://servicewechat.com/wx7ddec43d9d27276a/223/page-frame.html',
        'Connection':'keep-alive',
    }
    data = {
    "billCode": str(id),
    "orderCode": ""
    }
    res = request.post(url,headers=headers,data=data)
    # print(res.json())
    return res.json()['result']['orderCode']
    # f.write(str(id)+'======'+ str(res.json())+'\n')

def get_wx_detail_data():
    url = 'https://hdgateway.zto.com/searchOrderDetailByOrderCodeOrBillCode'
    headers = {
        'Host':'hdgateway.zto.com',
        'x-version':'V7.37.1',
        'charset':'utf-8',
        'x-oid':'oJpUI0dfodWhZGal6OKgt9-M0qZI',
        'content-type':'application/json',
        'User-Agent':'Mozilla/5.0 (Linux; Android 7.1.2; TAS-AN00 Build/TAS-AN00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3770.143 Mobile Safari/537.36 MMWEBID/3766 MicroMessenger/8.0.3.1880(0x28000334) Process/appbrand0 WeChat/arm32 Weixin NetType/WIFI Language/zh_CN ABI/arm32 MiniProgramEnv/android',
        'x-token':'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ0aGlyZFBhcnR5U2lnbiI6IlVTRVJDRU5URVIiLCJhdWQiOiJXZWJVc2VyQ2VudGVyIiwic3ViIjoiMzEwNDA0MDMiLCJjbGllbnRDb2RlIjoicGMiLCJpc3MiOiJXZWJVc2VyQ2VudGVyIiwiZmF0IjoxNjI2MzE3MjU2LCJtb2JpbGUiOiIxOTkyNDIzNzg4OSIsImV4cCI6MTYyNjMzODg1NiwiaWF0IjoxNjI2MzE3MjU2LCJ1c2VySWQiOiIzMTA0MDQwMyIsImp0aSI6IjdiNTU5YzhlYTAwMDQ0OGI4ZGJmMTBmNzg4ZGY1OTUyIn0.p6JTX07XCGvTezEk5yFreaNuRq313MtEd5tkykXroPxh_1bLzWUEYxWzTHRAgKpSLZGHG9FI0KXm84EeU_oQBPl0Svd0fGC5eIYmXEKaG2WKrMMFi5ysSy7vUX-XlANHZvxI3cWanfR2kTK8aGFUghmZMDpa1uQgMlD36s7c0bVt14oDGx2siQNNVpLJY2tmzDvFAFtslJhPwXmlMBDqTC_7AMpspMiJTfKjilzqgAzVswWulJjRCgfB0jL_qkIBFy5KPNJAySSoscvjimZIDD6s_Q3YVBjUUSr9-GvppANarHdxSKvNOQA1BRwLj8cTS0yHt-ablJ6_FyxjJRx2ew',
        'Accept-Encoding':'gzip,compress,br,deflate',
        'x-clientcode':'wechatMiniZtoHelper',
        'Referer':'https://servicewechat.com/wx7ddec43d9d27276a/223/page-frame.html',
        'Connection':'keep-alive',
    }
    # data = {
    # "billCode": str(id),
    # "orderCode": str(orderid)
    # }
    data = {
    "billCode": "75484411717564",
    "orderCode": "210705044981202107"
    }
    res = request.post(url,headers=headers,data=data)
    print(res.json())

    
if __name__ == "__main__":
    connet = pymysql.connect(host='192.168.0.14',port=3306,user='junfeng',passwd='Gzjunfeng888!',db='jf_python_db')
    cur = connet.cursor()
    # token = get_token()
    request = requests.session()
    request.mount('http://', HTTPAdapter(max_retries=3))
    request.mount('https://', HTTPAdapter(max_retries=3))
    # for pageIndex in tqdm(range(1667,3316)):
    #     print('----------------------第',pageIndex,'页------------------------------------------------')
    #     try:
    #         get_data(pageIndex,cur,token)
    #     except:
    #         token = get_token()
    #         get_data(pageIndex,cur,token)
    #     time.sleep(15)
    # cur.close()
    # token = get_token()
    # print(token)
    # get_wx_data()
    # WAYBILL_CODE
    # f = open('zt_wx_data.txt','a+')
    # df = pd.read_excel(r'./data_1.xlsx')
    # for i in range(len(df)):
    #     print(df['WAYBILL_CODE'][i])
    #     get_wx_detail(f,df['WAYBILL_CODE'][i])
    # f.close()
    # id = "75484411717564"
    # orderid = get_wx_detail("73158565701689")
    # print(orderid)
    # get_wx_detail_data()
